<template>
  <el-container>
    <el-main>
      <el-tabs type="border-card" v-model="activeName" @tab-click="changeHandler" class="tabs">
        <el-tab-pane v-for="item in list" :key="item.id" :label="item.achieveName" :name="item.id">
          <Achievement :tabs="item"></Achievement>
        </el-tab-pane>
        <el-tab-pane v-if="hasRole" label="全部信息" name="sixth">
          <el-container>
            <el-header height="35px">
              <el-button type="info" class="all-container" @click="toAddUserAchieve">添加</el-button>
              <el-dialog
                  title="用户新增"
                  :visible.sync="dialogVisibleAddUserAchieve"
                  width="30%"
                  :append-to-body="true">
                <el-form v-model="addUserAchieveForm" size="small" label-width="100px">
                  <el-form-item label="日期：">
                    <el-date-picker type="month" placeholder="选择日期" v-model="addUserAchieveForm.achieveTime" value-format="timestamp"></el-date-picker>
                  </el-form-item>
                  <el-form-item label="用户：">
                    <el-select placeholder="请选择用户" clearable filterable v-model="addUserAchieveForm.userId">
                      <el-option v-for="item in userList" :key="item.id" :label="item.userName" :value="item.id" />
                    </el-select>
                  </el-form-item>
                  <el-form-item label="子项：">
                    <el-select v-model="addUserAchieveForm.achieveId" clearable filterable placeholder="请选择项目" @change="selectChangeHandle">
                      <el-option v-for="item in allList" :key="item.id" :label="item.achieveName" :value="item.id" :disabled="item.fatherId === '0'"/>
                    </el-select>
                  </el-form-item>
                  <el-form-item label="数额：">
                    <el-input-number v-model="addUserAchieveForm.achieveNumber"/>
                  </el-form-item>
                  <el-form-item label="备注：">
                    <el-input v-model="addUserAchieveForm.remark" />
                  </el-form-item>
                  <el-form-item>
                    <el-button type="primary" @click="addUserAchieve">
                      确定
                    </el-button>
                    <el-button type="info" @click="addUserAchieveForm = {}">重置</el-button>
                  </el-form-item>
                </el-form>
              </el-dialog>
              <el-button type="primary" class="all-container" @click="toManagerTabs">标签管理</el-button>
              <el-dialog
                  title="查看"
                  :visible.sync="dialogVisible"
                  :modal-append-to-body="false"
                  width="60%">
                <div>
                  <el-tree
                      :data="list"
                      show-checkbox
                      node-key="id"
                      default-expand-all
                      :expand-on-click-node="false"
                      :props="defaultProps">
            <span class="custom-tree-node" slot-scope="{ node, data }">
            <span>{{ node.label }}</span>
            <span>
              <el-button
                  type="text"
                  size="mini"
                  @click="() => append(data)">
                新增
              </el-button>
              <el-button
                  type="text"
                  size="mini"
                  @click="() => toUpdateAchieve(data)">
                查看/修改
              </el-button>
              <el-button
                  type="text"
                  size="mini"
                  @click="() => remove(node, data)">
                删除
              </el-button>
            </span>
          </span>
                  </el-tree>
                  <el-dialog
                      title="查看/修改"
                      :visible.sync="dialogVisibleUpdate"
                      append-to-body
                      :modal="false"
                      width="30%">
                    <el-form :model="updateAchieveForm" label-width="100px" size="mini">
                      <el-form-item label="父级">
                        <el-select v-model="updateAchieveForm.fatherId" filterable clearable placeholder="选择父级">
                          <el-option v-for="item in allList" :key="item.id" :label="item.achieveName" :value="item.id"></el-option>
                        </el-select>
                      </el-form-item>
                      <el-form-item label="本级名称">
                        <el-input v-model="updateAchieveForm.achieveName" clearable></el-input>
                      </el-form-item>
                      <el-form-item label="基础绩点数">
                        <el-input-number v-model="updateAchieveForm.optionValue" :precision="3"></el-input-number>
                      </el-form-item>
                      <el-form-item label="最小绩点数：">
                        <el-input-number v-model="updateAchieveForm.minNumber" :precision="3"></el-input-number>
                      </el-form-item>
                      <el-form-item label="最大绩点数：">
                        <el-input-number v-model="updateAchieveForm.maxNumber" :precision="3"></el-input-number>
                      </el-form-item>
                      <el-form-item label="最大产值：">
                        <el-input-number v-model="updateAchieveForm.maxOptionValue" :precision="3"></el-input-number>
                      </el-form-item>
                      <el-form-item label="单位">
                        <el-input v-model="updateAchieveForm.unit" clearable></el-input>
                      </el-form-item>
                      <el-form-item>
                        <el-button type="primary" @click="updateAchieve">修改</el-button>
                        <el-button type="info" @click="dialogVisibleUpdate = false">取消</el-button>
                      </el-form-item>
                    </el-form>
                  </el-dialog>
                  <el-dialog
                      title="新增"
                      :visible.sync="dialogVisibleInVisible"
                      :append-to-body="true"
                      :modal="false"
                      width="30%">
                    <div>
                      <el-form :model="addForm" label-width="100px" size="mini">
                        <el-form-item label="父级">
                          <el-select v-model="addForm.fatherId" filterable clearable placeholder="选择父级">
                            <el-option v-for="item in allList" :key="item.id" :label="item.achieveName" :value="item.id"></el-option>
                          </el-select>
                        </el-form-item>
                        <el-form-item label="本级名称">
                          <el-input v-model="addForm.achieveName" clearable></el-input>
                        </el-form-item>
                        <el-form-item label="基础绩点数">
                          <el-input-number v-model="addForm.optionValue"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最小绩点数：">
                          <el-input-number v-model="addForm.minNumber" :precision="3" :step="0.1"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大绩点数：">
                          <el-input-number v-model="addForm.maxNumber" :precision="3" :step="0.1"></el-input-number>
                        </el-form-item>
                        <el-form-item label="最大产值：">
                          <el-input-number v-model="addForm.maxOptionValue" :precision="3" :step="0.1"></el-input-number>
                        </el-form-item>
                        <el-form-item label="单位">
                          <el-input v-model="addForm.unit" clearable></el-input>
                        </el-form-item>
                        <el-form-item>
                          <el-button type="success" @click="addAchieve">确定</el-button>
                          <el-button type="primary" @click="dialogVisibleInVisible = false">取消</el-button>
                        </el-form-item>
                      </el-form>
                    </div>
                  </el-dialog>
                </div>
              </el-dialog>

              <el-button type="success" class="all-container" @click="excelDownload" :loading="excelLoading">excel</el-button>

              <el-date-picker
                  class="all-container"
                  style="margin-left: 1%"
                  v-model="date"
                  type="month"
                  placeholder="日期选择"
                  @change="handleTimeChange">
              </el-date-picker>

              <el-select class="all-container" style="margin-left: 1%" v-model="userId" @change="handleUserChange" clearable filterable placeholder="请选择用户">
                <el-option
                    v-for="item in userList"
                    :key="item.id"
                    :label="item.userName"
                    :value="item.id">
                </el-option>
              </el-select>
            </el-header>
            <el-main>
              <!--          全部信息查看与管理-->
              <div>
                <el-table
                    :data="allData"
                    show-summary
                    :summary-method="getSummaries"
                    style="width: 100%">
                  <el-table-column
                      prop="achieveTime"
                      label="月份"
                      width="180"
                      :formatter="timeFormat2">
                  </el-table-column>
                  <el-table-column
                      prop="userId"
                      label="用户"
                      width="180"
                      :formatter="userInfoFormat">
                  </el-table-column>
                  <el-table-column
                      prop="achieveId"
                      label="子项"
                      width="180"
                      :formatter="achieveFormat">
                  </el-table-column>
                  <el-table-column
                      prop="achieveNumber"
                      label="数量"
                      width="180">
                  </el-table-column>
                  <el-table-column
                      prop="achievePrice"
                      label="产值"
                      width="180">
                  </el-table-column>
                  <el-table-column
                      prop="remark"
                      label="备注"
                      width="180">
                  </el-table-column>
                  <el-table-column
                      prop="createTime"
                      label="提交日期"
                      width="180"
                      :formatter="timeFormat">
                  </el-table-column>
                  <el-table-column
                      label="操作"
                      width="180"
                      fixed="right">
                    <template slot-scope="scope">
                      <el-button type="primary" size="mini" icon="el-icon-edit" circle @click="toUpdate(scope.row)"></el-button>
                      <el-button type="danger" size="mini" icon="el-icon-delete" circle @click="deleteUserAchieveById(scope.row)"></el-button>
                    </template>
                  </el-table-column>
                </el-table>
                <el-pagination
                    @size-change="handleSizeChange"
                    @current-change="handleCurrentChange"
                    :current-page="currentPage"
                    :page-sizes="[10, 20, 30, 40]"
                    :page-size="sizePage"
                    layout="total, sizes, prev, pager, next, jumper"
                    :total="totalPage">
                </el-pagination>
                <el-dialog
                    title="修改"
                    :visible.sync="dialogVisibleUpdateUserAchieve"
                    :append-to-body="true"
                    width="30%">
                  <el-form size="small" label-width="auto" v-model="updateUserAchieveForm">
                    <el-form-item label="时间：">
                      <el-date-picker type="month" placeholder="选择日期" v-model="updateAchieveTime" value-format="timestamp"></el-date-picker>
                    </el-form-item>
                    <el-form-item label="用户名：">
                      <el-select v-model="updateUserAchieveForm.userId" clearable filterable placeholder="请选择用户">
                        <el-option
                            v-for="item in userList"
                            :key="item.id"
                            :label="item.userName"
                            :value="item.id">
                        </el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="子项：">
                      <el-select v-model="updateUserAchieveForm.achieveId" filterable clearable placeholder="请选择">
                        <el-option v-for="item in allList" :key="item.id" :label="item.achieveName" :value="item.id"></el-option>
                      </el-select>
                    </el-form-item>
                    <el-form-item label="数量：">
                      <el-input-number v-model="updateUserAchieveForm.achieveNumber" />
                    </el-form-item>
                    <el-form-item label="产值：">
                      <el-input-number v-model="updateUserAchieveForm.achievePrice" />
                    </el-form-item>
                    <el-form-item>
                      <el-button type="primary" @click="updateUserAchieve">修改</el-button>
                      <el-button type="info" @click="dialogVisibleUpdateUserAchieve = false">取消</el-button>
                    </el-form-item>
                  </el-form>
                </el-dialog>
              </div>
            </el-main>

          </el-container>
        </el-tab-pane>
        <el-tab-pane label="绩效说明" name="seventh">
          <el-image :src="imgUrl"></el-image>
        </el-tab-pane>
      </el-tabs>
    </el-main>

  </el-container>
</template>

<script>
import Achievement from './component/achievement/Index'
import {add, deleteById, getAllList, getList, getAchieveById, update} from "@/api/Achievement";
import {addUserAchieve, allUserList, deleteUserAchieveById, excel, updateUserAchieve} from "@/api/UserAchieve";
import {formateDate} from "@/util/TimeFormat";
import {list} from "@/api/User";


export default {
  name: "Performance",
  data(){
    return{
      addForm: {},
      updateAchieveForm: {},
      updateUserAchieveForm: {},
      addUserAchieveForm: {},
      selectFormInputNumber: {},
      allData: [],
      dialogVisible: false,
      dialogVisibleInVisible: false,
      dialogVisibleUpdate: false,
      dialogVisibleUpdateUserAchieve: false,
      dialogVisibleAddUserAchieve: false,
      isMinValue: false,
      isMaxValue: false,
      isMaxPrice: false,
      treeData: [],
      defaultProps: {
        children: 'achievements',
        label: 'achieveName'
      },
      addUserAchieveProps: {
        value: 'id',
        label: 'achieveName',
        children: 'achievements'
      },
      userList: [],
      list: [],
      activeName: 'first',
      hasRole: false,
      date: '',
      allList: [],
      imgUrl: require('../../assets/app/WX20210507-144535@2x.png'),

      userId: '',

      updateAchieveTime: 0,

      currentPage: 1,
      sizePage: 10,
      totalPage: 0,

      excelLoading: false,
    }
  },

  components: {
    Achievement
  },

  created() {
    this.init()
  },

  methods: {

    conditionValue(val){
      if (val){
        return true
      }
    },

    selectChangeHandle(val){
      getAchieveById(val).then(res => {
        this.selectFormInputNumber = res.data.data.byId
        var selectFormInputNumber = this.selectFormInputNumber;
        // if (selectFormInputNumber.minNumber === null || selectFormInputNumber.minNumber === ''){
        //   console.log('selectFormInputNumber的最小值是null')
        //   selectFormInputNumber.minNumber = -Infinity
        // }
        // if (selectFormInputNumber.maxNumber === null || selectFormInputNumber.maxNumber === ''){
        //   console.log('selectFormInputNumber的最大值是null')
        //   selectFormInputNumber.maxNumber = Infinity
        // }
      })
    },

    addUserAchieve(){
      var addUserAchieveForm = this.addUserAchieveForm;
      var achieveTime = addUserAchieveForm.achieveTime;
      addUserAchieveForm.achieveTime = achieveTime / 1000
      addUserAchieve(addUserAchieveForm).then(res => {
        this.dialogVisibleAddUserAchieve = !this.dialogVisibleAddUserAchieve
        this.addUserAchieveForm = {}
        this.getUserAchieveList(this.currentPage, this.sizePage, this.date, this.userId)
        this.$notify.success(res.data.message)
      })
    },

    toAddUserAchieve(){
      this.dialogVisibleAddUserAchieve = true
    },

    handleUserChange(val){
      this.userId = val
      this.getUserAchieveList(1, this.sizePage, this.date, val)
    },

    handleTimeChange(val){
      this.date = val
      this.getUserAchieveList(1, this.sizePage, val, this.userId)
    },

    handleSizeChange(val) {
      this.sizePage = val
      this.getUserAchieveList(1, val, this.date, this.userId)
    },
    handleCurrentChange(val) {
      this.currentPage = val
      this.getUserAchieveList(val, this.sizePage, this.date, this.userId)
    },

    toUpdateAchieve(data){
      this.dialogVisibleUpdate = !this.dialogVisibleUpdate
      this.updateAchieveForm = data
    },

    changeHandler(val){
      console.log(val)
    },

    excelDownload(){
      this.excelLoading = true
      excel().then(res => {
        let data = res.data;
        let url = window.URL.createObjectURL(new Blob([data]));
        let link = document.createElement('a');
        link.style.display = 'none';
        link.href = url;
        link.setAttribute('download', '用户信息.xlsx');
        document.body.appendChild(link);
        link.click()
        this.excelLoading = false
      })
    },

    init(){
      this.auth()
      this.getInitAchieveList()
      this.getAllAchieveList()
      this.getUserList()
      this.getUserAchieveList(this.currentPage, this.sizePage, this.date, this.userId)
    },

    timeFormat2(row, col, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy年MM月")
    },

    timeFormat(row, col, cellValue, index){
      var date = new Date(cellValue * 1000);
      return formateDate(date, "yyyy年MM月dd日")
    },

    achieveFormat(row, col, cellValue, index){
      var achievements = this.allList
      for (let i = 0; i < achievements.length; i++) {
        if (achievements[i].id === cellValue + ""){
          return achievements[i].achieveName
        }
      }
    },

    userInfoFormat(row, col, cellValue, index){
      var userList = this.userList;
      for (let i = 0; i < userList.length; i++) {
        if (cellValue + "" === userList[i].id){
          return userList[i].userName
        }
      }
    },

    getInitAchieveList(){
      getList().then(res => {
        this.list = res.data.data.list;
        this.activeName = this.list[0].id
      }).catch()
    },

    auth(){
      var user = sessionStorage.getItem('userInfo')
      var userInfo = JSON.parse(user);
      var auth = userInfo.authorityList
      for (let i = 0; i < auth.length; i++) {
        if (auth[i].authority === "ROLE_root" || auth[i].authority === 'ROLE_admin') {
          this.hasRole = true
        }
      }
    },

    getAllAchieveList(){
      getAllList().then(res => {
        this.allList = res.data.data.list
      }).catch()
    },

    getUserAchieveList(pageNum,pageSize,time,userId){
      var date = new Date(time);
      var newTime = date.getTime() / 1000;
      if (newTime == null || isNaN(newTime)) newTime = 0
      allUserList(pageNum,pageSize,newTime,userId).then(res => {
        this.allData = res.data.data.list
        this.totalPage = res.data.data.total
      })
    },

    getUserList(){
      list().then(res => {
        this.userList = res.data.data.list
      })
    },

    handleClose(){

    },

    toManagerTabs(){
      this.dialogVisible = !this.dialogVisible
    },

    toUpdate(data){
      this.dialogVisibleUpdateUserAchieve = !this.dialogVisibleUpdateUserAchieve
      this.updateUserAchieveForm = data
      this.updateAchieveTime = this.updateUserAchieveForm.achieveTime * 1000
    },

    append(data){
      this.dialogVisibleInVisible = !this.dialogVisibleInVisible
    },

    updateAchieve(){
      let updateAchieveForm = this.updateAchieveForm;
      update(updateAchieveForm).then(res => {
        this.dialogVisibleUpdate = !this.dialogVisibleUpdate
        this.updateAchieveForm = {}
        this.$notify.success(res.data.message)
        this.getAllAchieveList()
        this.getInitAchieveList()
        this.getUserAchieveList(1, this.sizePage, this.date, this.userId)
      })
    },

    updateUserAchieve(){
      var updateUserAchieveForm = this.updateUserAchieveForm;
      updateUserAchieveForm.achieveTime = this.updateAchieveTime / 1000
      updateUserAchieve(updateUserAchieveForm).then(res => {
        this.$notify.success(res.data.message)
        this.dialogVisibleUpdateUserAchieve = !this.dialogVisibleUpdateUserAchieve
        this.updateUserAchieveForm = {}
        this.getUserAchieveList(1, this.sizePage, this.date, this.userId)
      })
    },

    remove(node, data){
      this.$confirm('确定删除吗？', { title: '提示', confirmButtonText: '确定', cancelButtonText: '取消' }).then( _ => {
        var id = data.id;
        deleteById(id).then(res => {
          const parent = node.parent;
          const children = parent.data.children || parent.data;
          const index = children.findIndex(d => d.id === data.id);
          children.splice(index, 1);
          this.$notify.success(res.data.message)
        })
      }).catch( _ => {

      })

    },

    addAchieve(){
      var addForm = this.addForm;
      if (addForm.fatherId === undefined || addForm.fatherId === ''){
        addForm.fatherId = 0
      }
      add(addForm).then(res => {
        var achieve = res.data.data.achieve;
        // const newChild = { id: achieve.id, label: addForm.achieveName, children: [] };
        if (!achieve.achievements) {
          this.$set(achieve, 'achievements', []);
        }
        achieve.achievements.push(achieve);
        this.dialogVisibleInVisible = false
        this.addForm = {}
        this.getInitAchieveList()
        this.getAllAchieveList()
        this.$notify.success(res.data.message)
      }).catch()
    },

    deleteUserAchieveById(data){
      this.$confirm('确认删除吗', { title: '提示', confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        deleteUserAchieveById(data.id).then(res => {
          this.$notify.success(res.data.message)
          this.allData.splice(this.allData.indexOf(data), 1)
          this.getUserAchieveList(1, this.sizePage, this.date, this.userId)
        })
      }).catch( _ => {
        this.$notify.warning('取消删除')
      })
    },

    deleteById(userAchieve){
      this.$confirm('确认删除吗', { title: '提示', confirmButtonText: '确定', cancelButtonText: '取消', type: 'warning' }).then(() => {
        deleteById(userAchieve.id).then(res => {
          this.$notify.success(res.data.message)
          this.tableData.splice(this.tableData.indexOf(userAchieve), 1)
        })
      }).catch( _ => {
        this.$notify.warning('取消删除')
      })

    },

    getSummaries(param){
      const { columns, data } = param;
      const sums = [];
      columns.forEach((column, index) => {
        if (index === 0) {
          sums[index] = '合计';
          return;
        }
        if (index === 1 || index === 2 || index === 5 || index === 6){
          sums[index] = '';
          return;
        }
        const values = data.map(item => Number(item[column.property]));
        if (!values.every(value => isNaN(value))) {
          sums[index] = values.reduce((prev, curr) => {
            const value = Number(curr);
            if (!isNaN(value)) {
              return prev + curr;
            } else {
              return prev;
            }
          }, 0);

          if (index === 3){
            sums[index] += ' 个';
          }

          if (index === 4){
            const sum = sums[index];
            sums[index] = sum.toFixed(2);
            sums[index] += ' 点';
          }
        } else {
          sums[index] = 'N/A';
        }
      });

      return sums;
    }
  }
}
</script>

<style scoped>
.tabs{
  width: 100%;
  margin: 0 auto;
  padding: 0 0;
}


.all-container{
  /*border: 1px solid black;*/
  float: left;
  margin-left: 1%;
}

.all-table{
  clear: both;
  margin-top: 1%;
}
</style>